package cn.tedu._05mvcboot03.controller;

import cn.tedu._05mvcboot03.conmon.reponse.JsonResult;
import cn.tedu._05mvcboot03.conmon.reponse.StataCode;
import cn.tedu._05mvcboot03.mapper.Usermapper;
import cn.tedu._05mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot03.pojo.entity.Article;
import cn.tedu._05mvcboot03.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users/")
@Validated
public class MvcController {
    @Autowired
    public Usermapper usermapper;

    @PostMapping("login")
    @ApiOperation(value = "用户登录功能")
    public JsonResult login(@RequestBody  UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.error("userLoginDTO:"+userLoginDTO);
        String username=userLoginDTO.getUsername();
        String password=userLoginDTO.getPassword();
        UserVO userVO = usermapper.loginSelect(username,password);
        log.debug("userVO:"+userVO);
        if (userVO==null){
            return new JsonResult(StataCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }

    @PostMapping("article")
    @ApiOperation("发表文章功能")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        log.error("userArticleDTO:"+userArticleDTO);
        UserVO userVO=(UserVO)session.getAttribute("user");
        Article article=new Article();
        article.setTitle(userArticleDTO.getTitle());
        article.setContent(userArticleDTO.getContent());
        article.setUserId(userVO.getId());
        usermapper.insert(article);
        return JsonResult.ok();
    }

    @GetMapping("selectByArticleId")
    @ApiOperation("查询指定文章功能")
    @ApiModelProperty(value = "文章id",dataType = "Long",required = true)
    private JsonResult selectByArticleId(@Range(min=1,max=100,message = "文章id必须在1-100之间")
                                             @RequestParam Long id){
        log.error("id:"+id);
        ArticleVO articleVO =usermapper.selectByArticleId(id);
        log.error("articleVO:"+articleVO);
        return JsonResult.ok(articleVO);
    }
}























